<template>

  <div class="app-container">
    <el-button type="primary" style="margin-bottom:24px;padding:16px 56px;" @click="showDiog">上传语音</el-button>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态">
          <el-option v-for="dict in dict.type.invoice_type" :key="dict.value" :label="dict.label" :value="dict.value">
          </el-option>
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="录音名称" prop="contactName">
        <el-input v-model="queryParams.contactName" placeholder="请输入录音名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <!-- <el-form-item label="日期" prop="createTime">
        <el-date-picker v-model="queryParams.createTime" type="date" placeholder="请选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item> -->
    </el-form>

    <el-table v-loading="loading" :data="customerListT" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="56" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="82" />
      <el-table-column label="上传人" align="center" prop="createBy" />
      <!-- <el-table-column prop="orderId" label="订单编号" show-overflow-tooltip align="center">
          </el-table-column> -->
      <el-table-column label="上传时间" align="center" prop="createTime" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == '0'">上传成功</el-tag>
          <el-tag v-if="scope.row.status == '1'">解析中</el-tag>
          <el-tag v-if="scope.row.status == '2'">分析排序中</el-tag>
          <el-tag v-if="scope.row.status == '3'">解析完成</el-tag>
          <el-tag v-if="scope.row.status == '4'">提交分析成功</el-tag>
          <el-tag v-if="scope.row.status == '5'">分析中</el-tag>
          <el-tag v-if="scope.row.status == '6'">分析完成</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:customer:edit']">修改</el-button> -->
          <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:customer:remove']">删除</el-button> -->
          <el-button size="mini" type="text" @click="handleNew(scope.row)"
            v-if="scope.row.status != '0' && scope.row.status != '1' && scope.row.status != '2' && scope.row.status != '5'"><el-tag>查看分段</el-tag></el-button>
          <el-button size="mini" type="text" @click="handleSegmentation(scope.row)"
            v-if="scope.row.segmented !== 'true' && scope.row.status == '3'"><el-tag
              type="warning">智能分段</el-tag></el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改客户信息对话框 -->
    <el-dialog title="新增客户" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="customerNameRRRR" placeholder="客户名称" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="remarkRRRR" placeholder="备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="acCust">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看客户详情抽屉 -->
    <el-drawer title="我是标题" :visible.sync="drawer" :with-header="false" :close-on-click-modal="false" size="80%">
      <!-- div -->
      <div class="drawerStyle">
        录音分段列表
      </div>
      <div class="drawerBtmStyle">
        <div>
          <!-- 分割场景（请勾选分割点） -->
          <!-- <el-button v-if="this.showCalVal" type="primary" @click="fengedian()">提交分割</el-button> -->
          <span style="margin-right:24px;"> 点击选择分割点 或</span>
          <el-button type="primary" @click="mergeAll()" v-if="this.tableData.length > 1">合并所有场景</el-button>
          <el-button type="primary" @click="newChangjing()">添加到新场景</el-button>
        </div>
        <div class="xiugaiStyle">
          <span @click="handleDeleteBatchModify"><i class="el-icon-edit-outline"></i>批量修改发言人</span>
        </div>
        <!--  @selection-change="handleSelectionChangeXunjia" 点击某一行  height="1000"-->
        <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%" 
          class="table-2" row-key="id" :tree-props="{ children: 'aiRecordingChildList' }" highlight-current-row
          @row-click="handleRowChick" @cell-mouse-enter="handleMouseEnter" @cell-mouse-leave="handleMouseLeave">
          <!-- <el-table-column type="selection" width="55" align="center" >
          </el-table-column> -->
          <el-table-column prop="" label="" align="center"></el-table-column>

          <el-table-column prop="id" label="id" align="center">
          </el-table-column>

          <el-table-column prop="customerName" label="客户名称" align="center" width="120">
            <template slot-scope="scope"
              v-if="scope.row.aiRecordingChildList && scope.row.aiRecordingChildList.length > 0">
              <div style="display: flex;align-items: center;">
                <el-input v-model="scope.row.customerName" placeholder="选择客户" disabled></el-input>
                <!-- 添加客户按钮 -->
                <el-button type="primary" size="mini" style="margin-left:4px;"
                  @click.native.stop="faddCustomerBtn(scope.row)">选择</el-button>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="rl" label="发言人" align="center">
          </el-table-column>
          <el-table-column prop="transcript" label="文字" style="display: flex;align-items: center;" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.transcript }}</span>
              <audio controls style="height:36px;width:100%;"
                v-if="!scope.row.aiRecordingChildList || scope.row.aiRecordingChildList.length === 0">
                <source :src="loadPath + scope.row.filePath" type="audio/mpeg">
              </audio>
            </template>
          </el-table-column>

          <el-table-column prop="spearName" label="说话人" align="center">
            <template slot-scope="scope"
              v-if="!scope.row.aiRecordingChildList || scope.row.aiRecordingChildList.length === 0">
              <el-tag>{{ scope.row.spearName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="recordDate" label="沟通时间" align="center">
            <template slot-scope="scope"
              v-if="scope.row.aiRecordingChildList && scope.row.aiRecordingChildList.length > 0">
              <el-date-picker v-model="scope.row.time" type="datetime" placeholder="选择时间" format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column prop="takec" label="音频时长" show-overflow-tooltip align="center">
          </el-table-column>
          <el-table-column prop="bgc" label="片段开始时间" show-overflow-tooltip align="center">
          </el-table-column>
          <el-table-column prop="egc" label="片段结束时间" show-overflow-tooltip align="center">
          </el-table-column>
        
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click.native.stop="handleSelect(scope.row)"
                v-if="!scope.row.aiRecordingChildList || scope.row.aiRecordingChildList.length === 0"
                icon="el-icon-discount">填写</el-button>
              <el-button size="mini" type="text" @click.native.stop="handleSelectSelf(scope.row)"
                v-if="!scope.row.aiRecordingChildList || scope.row.aiRecordingChildList.length === 0"
                icon="el-icon-discount">销售</el-button>
              <el-button size="mini" type="text" @click.native.stop="handleSelectSelfCustomer(scope.row)"
                v-if="!scope.row.aiRecordingChildList || scope.row.aiRecordingChildList.length === 0"
                icon="el-icon-discount">客户</el-button>
              <el-button size="mini" type="text" @click.native.stop="handleDeleteAudio(scope.row)"
                v-if="!scope.row.aiRecordingChildList || scope.row.aiRecordingChildList.length === 0"
                icon="el-icon-delete">删除</el-button>
              <el-button @click.native.stop="moveChildren(scope.row)"
                v-if="scope.row.aiRecordingChildList && scope.row.aiRecordingChildList.length > 0" size="mini"
                type="text">移动到该场景</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 使用 el-tooltip 作为提示 -->
        <div v-if="showTooltip" :style="tooltipStyle" class="custom-tooltip">
          {{ tooltipContent }}
        </div>
        
        <div class="btnEle" v-if="statusNum == 3">
          <el-button @click="toggleSelectionSave()" type="primary">保存</el-button>
          <el-button @click="toggleSelectionAxcure()">取消修改</el-button>
        </div>
      </div>
    </el-drawer>

    <el-dialog :title="titleT" :visible.sync="openSelect" width="500px" append-to-body :close-on-click-modal="false">
      <div style="display: flex;flex-direction: column;">
        <span style="margin-bottom:4px;">标记为：（<span style="color:#000;">如果是销售或者自己，请直接填写<i
              style="font-style: normal;color:red;font-weight:bold;">**销售**</i></span>）</span>
        <el-input v-model="speakerNameIndex"></el-input>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="AxcureBtn">确 定</el-button>
        <el-button @click="cancelBtn">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="批量修改发言人" :visible.sync="openSelectBatch" width="500px" append-to-body
      :close-on-click-modal="false">
      <span style="margin-bottom:4px;width:120px;text-align: right;">请选择发言人：</span>
      <el-select v-model="fayanren" placeholder="选择发言人" @change="changeSel">
        <el-option v-for="(item, index) in optionList" :key="index" :label="item.spearName" :value="item.spearName">
        </el-option>
      </el-select>

      <div style="display: flex;margin-top:12px;align-items: center;">
        <span style="width:120px;text-align: right;">发言人名称：</span>
        <el-input type="text" v-model="speakerNameIndexBatch"></el-input>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="AxcureBtnBatch">确 定</el-button>
        <el-button @click="cancelBtnBatch">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择客户 -->
    <el-dialog title="选择客户" :visible.sync="openSelectCustomer" width="500px" append-to-body
      :close-on-click-modal="false">
      <span style="margin-bottom:4px;width:120px;text-align: right;">选择客户：</span>
      <el-select v-model="changeCustomerVal" placeholder="选择客户">
        <el-option v-for="(item, index) in customerList" :key="index" :label="item.customerName" :value="item.id">
        </el-option>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="adCus">新增客户</el-button>
        <el-button type="primary" @click="AxcureCustomer">确 定</el-button>
        <el-button @click="cancelCustomer">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 上传语音弹窗 -->
    <el-dialog title="上传语音" :visible.sync="audioUpload" width="500px" append-to-body :close-on-click-modal="false">
      <div class="divStyle">
        <el-select v-model="language" placeholder="请选择语言类型">
          <el-option v-for="dict in dict.type.language_dict" :key="dict.value" :label="dict.label" :value="dict.value">
          </el-option>
        </el-select>
        <div style="margin:24px 0 0 0;">
          <span style="font-size:16px;">智能分段：</span><el-switch v-model="delivery"></el-switch>
        </div>
        <el-upload class="upload-demo" ref="upload" :file-list="fileList" :action="uploadImgUrl"
          :on-exceed="handleExceed" accept=".wav" :on-success="onSuccess" :on-remove="handleRemove" :auto-upload="true"
          :before-upload="beforeUpload" :headers="headers" :limit="5" :on-change="handleChange">
          <el-button slot="trigger" style="margin-top:24px;">+ 上传语音</el-button>
        </el-upload>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="audioSubmit">提交</el-button>
        <el-button @click="audioCancle">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { postAudioList, getCustomerlist, postVideo, submitData, listCustomer, getCustomer, delCustomer, addCustomer, updateCustomer, getChildlist, getSpokesmanList, postChangeName, postChangeNameBatch, postSegmented } from "@/api/system/audio";
import { getToken } from "@/utils/auth";
import axios from 'axios';

export default {
  name: "Customer",
  // 字典
  dicts: ['language_dict'],
  data() {
    return {
      fileList: '',
      filePathList: [],
      delivery: false,
      audioUpload: false,
      statusNum: '',
      selectIdRow: '',
      getIndexUser: '',
      showTooltip: false, // 是否显示提示
      tooltipContent: '', // 提示内容
      tooltipStyle: {
        // 提示框样式
        position: 'fixed',
        top: '0',
        left: '0',
        background: '#444',
        color: '#fff',
        padding: '8px',
        borderRadius: '4px',
        fontSize: '14px',
        zIndex: 9999,
      },
      refreshInterval: '',
      isRefreshing: false,
      childrenItem: [],
      selectedRow: '',
      selectedRows: '',
      customerListT: [],
      customerNameRRRR: '',
      remarkRRRR: '',
      time: '',
      batchId: '',
      custoRowId: '',
      changeCustomerVal: '',
      file: '',
      countdown: '',
      showCalVal: '',
      fileFf: '',
      aiDeepseekAnswerList: [],
      drawerNewt: false,
      language: '',
      fayanrenID: '',
      openSelectCustomer: false,
      openSelectBatch: false,
      rangeStr: '',
      videoLone: '',
      fayanren: '',
      speakerNameIndex: '',
      speakerNameIndexBatch: '',
      rowId: '',
      customerIds: [],
      customerNames: [],
      optionList: [],
      customerList: [],
      openSelect: false,
      headers: {
        'Authorization': 'Bearer ' + getToken(),
      },
      pusReturn: [],
      loadPath: process.env.VUE_APP_BASE_API,
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/system/file/fileUpload",
      multipleSelection: [],
      // 抽屉里面的音频列表
      tableData: [],
      tableDataTT: [],
      // 抽屉
      drawer: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 分段列表保存
      // rangeStr: [],
      // 弹出层标题
      title: "",
      titleT: '请标记客户/销售',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerName: null,
        phone: null,
        status: null,
        time: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        createBy: [
          { required: true, message: "创建者不能为空", trigger: "blur" }
        ],
        updateBy: [
          { required: true, message: "更新者不能为空", trigger: "blur" }
        ],
      }
    };
  },

  created() {
    // this.getList();
    this.isRefreshing = true;
    this.fetchData();  // 立即调用一次
    this.refreshInterval = setInterval(this.fetchData, 30000); // 每 30 秒刷新一次  },
  },

  activated() {
    this.isRefreshing = true;
    this.fetchData();  // 立即调用一次
    this.refreshInterval = setInterval(this.fetchData, 30000); // 每 30 秒刷新一次  },
  },

  methods: {
    // 清空上传文件
    clearFiles() {
      this.$refs.upload.clearFiles();
    },
    // 点击取消
    audioCancle() {
      this.audioUpload = false
      this.language = ''
      this.delivery = false
      this.filePathList = []
    },

    // 点击提交语音
    audioSubmit() {
      if (this.language == '' || this.filePathList.length == 0) {
        this.$message.warning('缺少填写项');
        return
      } else {
        let params = {
          filePathList: this.filePathList,
          segmented: this.delivery.toString(),
          languages: this.language
        }
        this.loading = true
        postAudioList(params).then(res => {
          this.loading = false
          this.$message.success('上传成功')
          this.getList()
          this.audioCancle()
        })
      }
    },
    // 添加弹窗
    showDiog() {
      this.audioUpload = true
      this.clearFiles()
    },
    // 智能分段
    handleSegmentation(row) {
      let params = {
        id: row.id
      }
      postSegmented(params).then(res => {
        this.$message.success(res.msg)
        this.getList()
      })
    },

    // 鼠标进入单元格时触发
    handleMouseEnter(row, column, cell, event) {
      this.showTooltip = true; // 显示提示
      this.tooltipContent = `可点击，从当前选择的行开始分割到新场景`; // 设置提示内容
      // 动态设置提示框位置
      this.tooltipStyle.left = `${event.clientX + 10}px`; // 鼠标右侧 10px
      this.tooltipStyle.top = `${event.clientY + 10}px`;
    },
    // 鼠标离开单元格时触发
    handleMouseLeave() {
      this.showTooltip = false; // 隐藏提示
    },

    // 刷新列表
    fetchData() {
      try {
        this.getList()
      } catch (error) {
        console.error('获取数据失败:', error);
      }
    },

    // 停止定时刷新
    stopRefresh() {
      if (this.refreshInterval) {
        console.log('定时器已停止');
        clearInterval(this.refreshInterval);
        this.refreshInterval = null;
      } else {
        console.log('没有定时器需要清理');
      }
    },

    // 添加到新场景
    newChangjing() {
      let selCj = this.selectedRows
      if (selCj.length == []) {
        this.$message.error('请选择要添加的分段')
        return
      } else {
        // 遍历选中的行
        let params = {
          updateTime: '',
          updateBy: '',
          transcript: '',
          time: '',
          take: '',
          status: '',
          remark: '',
          orderId: '',
          mainId: '',
          id: '',
          duan: '',
          delFlag: '',
          customerName: '',
          customerId: '',
          createTime: '',
          createById: '',
          createBy: '',
          batchId: '',
          answerMap: {},
          aiRecordingChildList: [],
          aiDeepseekSpokesmanList: [],
          aiDeepseekAnswerList: []
        }
        // 在当前tableData中的索引前添加
        this.tableData.forEach((item, index) => {
          if (index == this.getIndexUser) {
            params.aiRecordingChildList = this.selectedRows
            this.tableData.splice(index, 0, params)
          }
        })
        // 获取 selectedRows 中的所有 id
        let selectedIds = this.selectedRows.map(row => row.id);
        let cc = []
        this.tableData[Number(this.getIndexUser) + 1].aiRecordingChildList.filter(item => {
          if (!selectedIds.includes(item.id)) {
            cc.push(item)
          }
        })

        this.tableData[Number(this.getIndexUser) + 1].aiRecordingChildList = cc
        // 给每个数据赋值并排序
        this.tableData.forEach((item, index) => {
          item.id = index + 1
          item.aiRecordingChildList.sort((a, b) => {
            return a.id - b.id;
          })
        })
        // 去掉重复项
        this.tableData = this.tableData.filter((item) => {
          return item.aiRecordingChildList && item.aiRecordingChildList.length > 0;
        });

        this.selectedRows = ''
        this.selectedRow = ''
        this.$message.success("添加成功");
      }
    },

    // 选中行
    handleRowChick(row) {
      // 拿到选中的id
      this.selectIdRow = row.id
      // 从当前选择的行开始分割到新场景
      // this.multipleSelection.push(row)
      // 清空
      this.selectedRows = ''
      this.selectedRow = ''
      //  2.找到选择到那一项的父元素
      let getIndex = -1;
      outerLoop: for (let i = 0; i < this.tableData.length; i++) {
        const item = this.tableData[i];
        for (let j = 0; j < item.aiRecordingChildList.length; j++) {
          const item2 = item.aiRecordingChildList[j];
          if (String(item2.id) == String(row.id)) {
            getIndex = i;
            break outerLoop; // 找到符合条件的项后停止外层循环
          }
        }
      }
      this.getIndexUser = getIndex
      var result = []; // 存放结果的空数组
      result = this.tableData[getIndex]
      let cct = []
      // 筛选出小于那一项id的数据
      if (result?.aiRecordingChildList && row) {
        // 使用 filter 筛选符合条件的项
        const filteredItems = result.aiRecordingChildList.filter(item => item.id <= row.id);
        // 将筛选结果添加到 cct 中
        cct.push(...filteredItems);
      }
      // 拿到最后点击的id
      this.selectedRows = cct
    },

    // 移动到该场景
    moveChildren(targetRow) {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请先选择要移动的数据");
        return;
      }
      // 点击移动到该场景的索引
      let selfIndex = Number(targetRow.id) - 1
      // 拿到选中的行的索引的
      let getIndexUser = Number(this.getIndexUser)
      // 1.拿到索引之间的item
      if (getIndexUser > selfIndex) {
        console.log('向上移动')
        let detAry = []
        let ids = []
        for (let i = selfIndex; i < getIndexUser; i++) {
          ids.push(i)
          this.tableData[i].aiRecordingChildList.forEach(item => {
            detAry = detAry.concat(this.tableData[i].aiRecordingChildList); // 合并子列表
          })
        }
        this.selectedRows.forEach(item => {
          detAry.push(item)
        })
        // 2. 将合并后的数据赋值给目标行
        this.tableData[selfIndex].aiRecordingChildList = detAry;

        // 3. 删除选中的行数据
        let selectedIds = this.selectedRows.map(row => row.id); // 获取选中行的 id
        this.tableData[getIndexUser].aiRecordingChildList = this.tableData[getIndexUser].aiRecordingChildList.filter(
          item => !selectedIds.includes(item.id)
        );

        // 4. 删除中间的行
        const idsAry = ids.slice(1); // 排除目标行
        this.tableData = this.tableData.filter((item, index) => !idsAry.includes(index));
        // 5. 重新排序并去重
        this.tableData.forEach((item, index) => {
          item.id = index + 1; // 重新设置 id
          if (item.aiRecordingChildList) {
            // 排序
            item.aiRecordingChildList.sort((a, b) => a.id - b.id);
            // 去重
            let uniqueList = [];
            let seenIds = new Set();
            item.aiRecordingChildList.forEach(itemTT => {
              if (!seenIds.has(itemTT.id)) {
                uniqueList.push(itemTT);
                seenIds.add(itemTT.id);
              }
            });
            item.aiRecordingChildList = uniqueList;
            console.log('aiRecordingChildList', item.aiRecordingChildList)
          }
        });
        this.$forceUpdate(); // 强制更新视图

      } else if (getIndexUser < selfIndex) {
        console.log('向下移动')
        let detAry = []
        let ids = []
        for (let i = getIndexUser; i < selfIndex; i++) {
          ids.push(i)
        }

        // 拿到所有的项
        var idsAry = ids.slice(1); // 排除目标行
        if (idsAry == '' || idsAry.length == 0) {
          idsAry = [0]
        } else {
          this.tableData.forEach((item, index) => {
            idsAry.forEach((item2) => {
              if (item2 == index) {
                item.aiRecordingChildList.forEach(item3 => {
                  detAry.push(item3)
                })
              }
            })
          })
        }
        // 3. 找到当前项中的每一项
        let selectedIds = this.selectedRows.map(row => row.id) // 获取选中行的 id
        selectedIds.splice(0, -1); // 清空 selectedIds 或根据需求调整
        this.tableData[getIndexUser].aiRecordingChildList.forEach(item2 => {
          if (!selectedIds.includes(item2.id)) { // 只添加不在 selectedIds 中的项
            detAry.push(item2);
          }
        });
        detAry.forEach(item => {
          this.tableData[selfIndex].aiRecordingChildList.push(item)
        })

        // this.tableData[selfIndex].aiRecordingChildList = detAry
        // 过滤掉不需要的项，保留 selectedIds 中的项
        this.tableData[getIndexUser].aiRecordingChildList = this.tableData[getIndexUser].aiRecordingChildList.filter(
          item => selectedIds.includes(item.id) // 保留不在 selectedIds 中的项
        );

        if (idsAry.length == 1 && idsAry[0] == 0 || idsAry == '') {
          console.log('不需要删除')
        } else {
          this.tableData = this.tableData.filter((item, index) => !idsAry.includes(index));
        }

        //  移除重复项
        // let dfe = []
        // this.tableData[getIndexUser].aiRecordingChildList.forEach(item => {
        //   dfe.push(item.id)
        // })
        // let feas = []
        // this.tableData[getIndexUser + 1].aiRecordingChildList.forEach(item => {
        //   feas.push(item.id)
        // })
        // let dfe2 = feas.filter(item => !dfe.includes(item))
        // this.tableData[getIndexUser + 1].aiRecordingChildList.forEach(item => {
        //   if (!dfe2.includes(item.id)) {
        //     this.tableData[getIndexUser + 1].aiRecordingChildList.splice(this.tableData[getIndexUser + 1].aiRecordingChildList.indexOf(item), 1)
        //   }
        // })

        // 5. 重新排序并去重
        this.tableData.forEach((item, index) => {
          item.id = index + 1; // 重新设置 id
          if (item.aiRecordingChildList) {
            // 排序
            item.aiRecordingChildList.sort((a, b) => a.id - b.id);
            // 去重
            let uniqueList = [];
            let seenIds = new Set();
            item.aiRecordingChildList.forEach(itemTT => {
              if (!seenIds.has(itemTT.id)) {
                uniqueList.push(itemTT);
                seenIds.add(itemTT.id);
              }
            });
            item.aiRecordingChildList = uniqueList;
          }
        });
        this.$forceUpdate(); // 强制更新视图
      } else {
        console.log('自身无需移动')
      }
      // 过滤数组为空的一项 this.tableData =
      this.tableData = this.tableData.filter((item) => {
        return item.aiRecordingChildList && item.aiRecordingChildList.length > 0;
      });

      this.selectedRows = ''
      this.selectedRow = ''
      this.$message.success("数据移动成功");
    },

    // 点击确定
    acCust() {
      this.open = false
      let params = {
        customerName: this.customerNameRRRR,
        remark: this.remarkRRRR
      }
      addCustomer(params).then(res => {
        this.$message.success(res.msg)
        getCustomerlist().then(res => {
          this.customerList = res.data
        })
      })
    },

    adCus() {
      this.open = true
    },

    // 合并所有
    mergeAll() {
      this.selectedRows = ''
      this.selectedRow = ''
      var aiRecord = []
      this.tableData.forEach((item, index) => {
        item.aiRecordingChildList.forEach(item2 => {
          aiRecord.push(item2)
        })
      })
      this.tableData[0].aiRecordingChildList = aiRecord
      let cc = []
      cc.push(this.tableData[0])
      this.tableData = cc
      this.tableData.forEach((item, index) => {
        item.aiRecordingChildList.sort((a, b) => {
          return a.id - b.id;
        });
        item.id = index + 1
      })
    },

    // 选择客户
    faddCustomerBtn(row) {
      this.custoRowId = row.id
      this.openSelectCustomer = true
      // 调用客户列表
      getCustomerlist().then(res => {
        this.customerList = res.data
      })
    },

    AxcureCustomer(row) {
      let tableDa = this.tableData
      tableDa.forEach(item => {
        if (item.id == this.custoRowId) {
          item.customerId = this.changeCustomerVal
          item.customerName = this.customerList.find(item2 => item2.id == this.changeCustomerVal).customerName
        }
      })
      this.tableData = tableDa
      setTimeout(() => {
        this.openSelectCustomer = false
      }, 500)
    },

    cancelCustomer() {
      this.openSelectCustomer = false
    },

    // 触发文件选择
    triggerFileInput() {
      if (this.language == '') {
        this.$message.warning('请选择语言')
        return
      } else {
        this.$refs.fileInput.click(); // 触发文件选择对话框
      }
    },

    // 处理文件选择
    handleFileChange(event) {
      this.file = event.target.files[0]; // 获取选择的文件
      const maxSize = 500 * 1024 * 1024; // 500MB

      if (this.file && this.file.size > maxSize) {
        console.log('不能超过500M')
        this.$message.warning('文件不能超过500M，请重新选择！')
        event.target.value = ''; // 清空文件输入
      } else {
        this.errorMessage = '';
        // 处理文件上传逻辑
        this.uploadFile();
      }
    },

    // 上传文件
    async uploadFile() {
      if (!this.file) {
        this.$message.error('请选择一个文件');
        return;
      }
      if (this.file) {
        if (this.validateFile(this.file)) {
          // 处理文件上传逻辑
          console.log('文件验证通过，开始上传...');
          this.loading = true
          // 创建 FormData 对象
          const formData = new FormData();
          formData.append('file', this.file); // 添加文件
          formData.append('language', this.language); // 添加语言
          try {

            // fileUpload(formData).then(response => {
            //   // this.form = response.data;
            //   // this.open = true;
            //   // this.title = "修改客户信息";
            // });

            // 发送请求
            const token = localStorage.getItem('token');
            const response = await axios.post('/dev-api/system/aimain/fileUpload', formData, {
              headers: {
                'Content-Type': 'multipart/form-data', // 设置请求头
                'Authorization': "Bearer " + getToken()
              },
            });
            // Authorization: "Bearer " + getToken()
            this.loading = false
            this.$message.success('上传成功')
            this.getList();
          } catch (error) {
            console.error('上传失败:', error);
            this.$message.error('上传失败')
          }

        } else {
          // 格式不对
          this.$message.error('请上传有效的 WAV 文件');
        }
      }
    },

    validateFile(file) {
      // 验证文件扩展名
      const validExtensions = ['.wav'];
      const fileExtension = file.name.slice(file.name.lastIndexOf('.')).toLowerCase();
      if (!validExtensions.includes(fileExtension)) {
        return false;
      }
      // 验证 MIME 类型
      const validMimeTypes = ['audio/wav'];
      if (!validMimeTypes.includes(file.type)) {
        return false;
      }
      return true;
    },

    // 标记为销售
    handleSelectSelf(row) {
      let dc = this.tableData
      dc.forEach(item => {
        item.aiRecordingChildList.forEach(item2 => {
          if (item2.id == row.id) {
            item2.spearName = '销售'
          }
        })
      })
      this.$nextTick(() => {
        this.tableData = dc
      })
    },

    // 标记为客户
    handleSelectSelfCustomer(row) {
      let dc = this.tableData
      dc.forEach(item => {
        item.aiRecordingChildList.forEach(item2 => {
          if (item2.id == row.id) {
            item2.spearName = '客户'
          }
        })
      })
      this.$nextTick(() => {
        this.tableData = dc
      })
    },

    // 提交分割点
    fengedian() {
      this.toggleSelectionSave()
    },

    //  批量修改
    handleDeleteBatchModify() {
      this.openSelectBatch = true
      let params = {
        mainId: this.rowId,
        batchId: this.batchId
      }
      getSpokesmanList(params).then(res => {
        this.optionList = res.data
      })
    },

    // 选择发言人
    changeSel(e) {
      console.log('sdf', e)
    },

    handleChange(file, fileList) {
      if (file.status === 'ready') {
        console.log('队列', file)
      } else if (file.status === 'uploading') {
        this.$message.warning('文件正在上传');
        console.log('文件正在上传'); // 文件正在上传中
      } else if (file.status === 'success') {
        let msgAry = []
        console.log('文件上传成功fileList', fileList); // 文件上传成功
        fileList.forEach(item => {
          msgAry.push(item.response.msg)
        })
        this.filePathList = msgAry
      } else if (file.status === 'error') {
        console.log('文件上传失败'); // 文件上传失败
      }
    },

    // 删除
    handleDeleteAudio(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除该分段？').then(function () {
        return delCustomer(ids);
      }).then(() => {
        // 获取分段列表
        let params = {
          mainId: this.rowId,
          batchId: this.batchId

        }
        getChildlist(params).then(res => {
          let listAry = res.data
          listAry.forEach((item, index) => {
            item.id = index + 1
            item.aiRecordingChildList.forEach(item2 => {
              item2.bgc = item2.bg / 1000 + 's'
              item2.egc = item2.eg / 1000 + 's'
              item2.takec = item2.take / 1000 + 's'
            })
          })
          this.tableData = listAry
        })
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },

    // 点击确定
    AxcureBtn() {
      this.tableData.forEach(item => {
        item.aiRecordingChildList.forEach(item2 => {
          if (item2.id == this.fayanrenID) {
            item2.spearName = this.speakerNameIndex
          }
        })
      })
      this.openSelect = false
    },

    // 取消
    cancelBtn() {
      this.openSelect = false
    },

    // 批量确定
    AxcureBtnBatch() {
      if (this.fayanren == '' || this.speakerNameIndexBatch == '') {
        this.$message.warning('缺少填写项');
        return
      } else {
        this.tableData.forEach(item => {
          item.aiRecordingChildList.forEach(item2 => {
            if (item2.rl == this.fayanren) {
              item2.spearName = this.speakerNameIndexBatch
            }
          })
        })
        setTimeout(() => {
          this.openSelectBatch = false
        }, 500)
      }
    },

    // 批量修改取消
    cancelBtnBatch() {
      this.openSelectBatch = false
    },

    //  选择发言人
    handleSelect(row) {
      this.fayanrenID = row.id
      this.openSelect = true
    },

    // 上传文件相关
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },

    beforeUpload(file) {
      // 验证文件类型
      const isWav = file.type === 'audio/wav' || file.name.endsWith('.wav');
      if (!isWav) {
        this.$message.error('只能上传 .wav 文件');
        return false; // 阻止上传
      }

      // 验证文件大小（例如限制为 500MB）
      const isLt10M = file.size / 1024 / 1024 < 500;
      if (!isLt10M) {
        this.$message.error('文件大小不能超过 500MB');
        return false; // 阻止上传
      }

      // 其他自定义验证逻辑
      // ...
      return true; // 允许上传
    },

    handleExceed(files, fileList) {
      this.$message.warning('超出文件数量限制');
    },

    onSuccess(res, file, fileList) {
      // console.log('ffuuuuuuule', file)
      // this.filePathList = file
      if (res.code == 500) {
        this.$message.warning(res.msg);
      } else {
        this.$message.success(res.msg);
        this.getList();
      }
    },

    // 上传音频限制
    handleExceed(files, fileList) {
      this.$message.warning(`超出文件数量`);
    },

    //  点击保存
    toggleSelectionSave() {
      // console.log('[table]',this.tableData)
      for (let item of this.tableData) {
        if (item.customerName == null || item.customerName == '') { // 检查 input 是否为空
          this.$message.error('缺少填写项，请选择客户')
          return; // 停止进一步操作
        }
        if (item.time == null || item.time == '') { // 检查 input 是否为空
          this.$message.error('缺少填写项，请选择日期')
          return; // 停止进一步操作
        }
      }
      
      const hasSales = this.tableData.some(item =>
        item.aiRecordingChildList.some(item =>
           String(item.spearName).includes("销售")
        )
      );

      if (!hasSales) {
        this.$message.error("表格中没有包含 '销售' 的角色"); // 使用 Element Plus 的提示组件
        return
      }

      // 处理数据
      let itemAry = []
      this.tableData.forEach(item => {
        let obj = {
          duan: item.duan,
          customerName: item.customerName,
          customerId: item.customerId,
          time: item.time,
        }
        let aiRecord = []
        item.aiRecordingChildList.forEach(item2 => {
          let objT = {
            childId: item2.id,
            speaker: item2.spearName
          }
          aiRecord.push(objT)
        })
        obj.aiDeepseekSpokesmanList = aiRecord
        itemAry.push(obj)
      })

      let params = {
        id: this.rowId,
        batchId: this.batchId,
        aiRecordingDuanList: itemAry
      }
      postChangeName(params).then(res => {
        this.$modal.msgSuccess(res.msg);
        // this.drawer = false;
        // 获取分段列表
        let params = {
          mainId: this.rowId,
          batchId: this.batchId
        }
        getChildlist(params).then(res => {
          let listAry = res.data
          listAry.forEach((item, index) => {
            item.id = index + 1
            item.aiRecordingChildList.forEach(item2 => {
              item2.bgc = item2.bg / 1000 + 's'
              item2.egc = item2.eg / 1000 + 's'
              item2.takec = item2.take / 1000 + 's'
            })
          })
          this.tableData = listAry
        })
      })
      this.drawer = false;
      this.getList()

    },

    // 点击取消修改
    toggleSelectionAxcure() {
      let params = {
        mainId: this.rowId,
        batchId: this.batchId
      }
      getChildlist(params).then(res => {
        let listAry = res.data
        listAry.forEach((item, index) => {
          item.id = index + 1
          item.aiRecordingChildList.forEach(item2 => {
            item2.bgc = item2.bg / 1000 + 's'
            item2.egc = item2.eg / 1000 + 's'
            item2.takec = item2.take / 1000 + 's'
          })
        })
        this.tableData = listAry
        this.$forceUpdate()
      })
    },

    // 点击取消
    toggleSelection(rows) {
      this.$refs.multipleTable.clearSelection();
      // this.drawer = false
      // this.pusReturn = []
      // console.log('multipleSelection', this.multipleSelection)
    },

    // 查看详情
    handleNew(row) {
      this.statusNum = row.status
      // 调用详情
      this.rowId = row.id
      this.batchId = row.batchId
      this.rangeStr = row.rangeStr
      let params = {
        mainId: row.id,
        batchId: row.batchId
      }
      this.drawer = true

      // 获取分段列表
      getChildlist(params).then(res => {
        let listAry = res.data
        listAry.forEach((item, index) => {
          item.id = index + 1
          item.aiRecordingChildList.forEach(item2 => {
            item2.bgc = item2.bg / 1000 + 's'
            item2.egc = item2.eg / 1000 + 's'
            item2.takec = item2.take / 1000 + 's'
          })
        })
        this.tableData = listAry
      })
    },

    /** 查询客户信息列表 */
    getList() {
      this.loading = false
      this.loading = true;
      listCustomer(this.queryParams).then(response => {
        this.customerListT = response.rows;
        this.rangeStr = response.rows.rangeStr;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        customerName: null,
        phone: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        status: null
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增客户";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCustomer(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改客户信息";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.loading = true;
      // 数据循环提取id
      // 数据循环提取名字
      this.totalData.forEach(item => {
        this.customerIds.push(item.id)
        this.customerNames.push(item.customerName)
      })
      this.customerIds.toString()
      this.customerNames.toString()

      this.$refs["form"].validate(valid => {
        this.loading = false;
        if (valid) {
          if (this.form.id != null) {
            updateCustomer(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCustomer(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    // handleDelete(row) {
    //   console.log('sdfsdf',row.id)
    //   const ids = row.id || this.ids;
    //   this.$modal.confirm('是否确认删除该片段"' + ids + '"的数据项？').then(function () {
    //     return delCustomer(ids);
    //   }).then(() => {
    //     // 获取分段列表
    //     getChildlist(params).then(res => {
    //       let listAry = res.data
    //       listAry.forEach(item => {
    //         item.childList.forEach(item2 => {
    //           item2.bg = item2.bg / 1000 + 's'
    //           item2.eg = item2.eg / 1000 + 's'
    //           item2.take = item2.take / 1000 + 's'
    //         })
    //       })
    //       this.tableData = listAry
    //     })
    //     this.$modal.msgSuccess("删除成功");
    //   }).catch(() => { });
    // },
  },

  beforeRouteLeave(to, from, next) {
    this.stopRefresh();
    next(); // 确保调用next()以允许路由离开
  },

};
</script>

<style>
.drawerStyle {
  padding: 24px;
}

.drawerBtmStyle {
  padding: 24px;
}

.btnEle {
  margin-top: 24px;
}

/* .styleBtm{
  margin-bottom:24px;
  padding:24px 42px;
}

.styleBtm .el-button{
  padding:18px 54px;
  font-size:18px;
} */

.divStyle {
  padding: 24px 0;
  /* display: flex; */
}

/* .divStyle .el-button {
  padding: 14px 46px;
  font-size: 18px;
} */

.xiugaiStyle {
  color: #1890ff;
  margin: 0 24px 12px 0;
  text-align: right;
  cursor: pointer;

}

.xiugaiStyle span {
  border: 1px solid #1890ff;
  padding: 12px;
  display: inline-block;
  border-radius: 8px;
}

.xiugaiStyle:hover {
  color: #76b8f5;
}

.drawerStyle {
  padding: 24px;
  font-weight: bold;
}

.drawerBtmStyle {
  padding: 24px;
}

.btnEle {
  margin-top: 24px;
}

.divStyle {
  padding: 24px 0;
}

.divStyle .el-button {
  padding: 14px 46px;
  font-size: 18px;
}

.backStyle {
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 16px;
}

.oldSpan {
  background: #e8f4ff;
  border: 1px solid #d1e9ff;
  color: #1890ff;
  margin-right: 12px;
}

.highSpan {
  background: #e7faf0;
  border: 1px solid #d0f5e0;
  color: #13ce66;
}

.descript {
  border: 1px solid #e6ebf5;
  border-radius: 8px;
  padding: 12px;
}

.descript p {
  margin: 0 !important;
}

.contentP {
  color: #333;
  line-height: 32px;
}

.spanStyle {
  background: #ffdbda;
  color: #ff000c;
  border: 1px solid #f5d0d8;
  display: inline-block;
}

.styleCol {
  color: #333;
  display: inline-block;
}

.huag {
  color: #606266;
  margin-left: 24px;
}

.adBgcol {
  background: #eff6fe;
  display: flex;
  align-items: flex-start;
  padding: 12px;
  margin-top: 12px;
  border-radius: 8px;
  flex: 1;
  margin-right: 12px;
}

.adBgcol P {
  padding: 12px;
  display: flex;
  align-items: flex-start;
  flex-direction: column;
  padding: 0;
  margin: 0;
  color: #606266;
}

.adBgcol P:nth-child(1) {
  margin-right: 32px;
}

.adBgcol P span:nth-child(1) {
  margin-bottom: 12px;
}

.huagongSize {
  color: #1890ff;
  font-size: 14px;
}

.adBgcol P:nth-child(2) {
  font-size: 14px;
}

.spanStyleSize {
  background: #ffdbdac5;
  color: #ff000c;
  border: 1px solid #f5d0d8;
}

.backStyleSize {
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 12px;
  margin-right: 6px;
  display: flex;
  align-items: center;
}

.spanStyleSizeSuccess {
  background: #d6f7e9;
  color: #186d47;
  border: 1px solid #e2f5d0;
}

.backStyleSize i {
  border-radius: 100%;
  display: inline-block;
  width: 14px;
  height: 14px;
  font-size: 8px;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 4px;
  padding-top: 2px;
  font-style: normal;
}

.istyle {
  border: 1px solid #186d47;
}

.istyleT {
  border: 1px solid red;
}

.tzStyl {
  padding: 0 0 0 24px;
  color: #606266;
  margin-bottom: 36px;
  /* background: ; */
}

.highlight {
  background-color: #f0f9eb;
  /* 设置高亮背景色 */
}

/* .el-table__body-wrapper tbody tr {
  cursor: grab;
} */

.table-2 .el-input {
  width: 100%;
  /* 使 input 填满单元格 */
  font-size: 14px;
  padding: 0 !important;
}

.table-2 .el-input .el-input__inner {
  padding: 0 !important;
  text-align: center;
}

.table-2 .el-input__prefix {
  display: none !important;
  width: 100% !important;
}

.table-2 .el-button--mini {
  padding: 7px 2px !important;
}

.custom-tooltip {
  pointer-events: none;

  /* 防止提示框遮挡鼠标事件 */
}
</style>
